#include"receiver.h"


using namespace std;






/***************************************
			Class Receiver
***************************************/


Receiver::Receiver()
{
	receiver_running = true;

	server_port = 8888;
	receiver_running = true;
}

Receiver::~Receiver()
{
}


void
Receiver::stop_receiver()
{
	receiver_running = false;
}


void 
Receiver::run_receiver()
{
	int lsock = -1;
	m_clock.set_mode(1);

	lsock = udp_open();
	udp_reuse_address(lsock);
	udp_bind(lsock, 0, 8888);
	udp_listen(lsock, 1);
	udp_nonblock(lsock);

	while(1)
	{
		m_clock.click();

		if(receiver_running == false)
		{
			ColorPrint::printRed("receiver time out!\n");
			break ;
		}

		int ip = 0;
		int port = 0;

		bzero(buff, sizeof(buff));
		int count = udp_recvfrom(lsock, buff, sizeof(buff), &ip, &port);
		if(count>0)
		{
			//buff[sizeof(sizeof(buff)-1)]=0;
			printf("recv:%s/%d\n", buff, count);


			bzero(data, sizeof(data));
			strcpy(data, m_clock.strTimeClicked);
			/*
			strcpy(data, buff);
			strcat(data, "/");
			strcat(data, m_clock.strTimeClicked);
			*/
			udp_sendto(lsock, data, strlen(data), ip, port);

			printf("send:%s \n", data);
		}
		else
		{
			if(strcmp(m_clock.strTimeClicked, m_clock.strTimeClicked_last)!=0)
			{
				//printf("lsock(%d)\n", lsock);
			}	
		}
	}
	
//	ColorPrint::printYellow("udp close\n");
	udp_close(lsock);
	return ;
}


/***************************************
			Class ReceiverController
***************************************/

Receiver *ReceiverController::udpCs_ptr	= NULL;

void
ReceiverController::udpCs_install( Receiver *udpCs )
{
	udpCs_ptr = udpCs ;
}
void
ReceiverController::udpCs_stop_receiver()
{
	udpCs_ptr->stop_receiver();
}

/***************************************
			Class ReceiverThread
***************************************/
ReceiverThread::ReceiverThread()
{
}

ReceiverThread::~ReceiverThread()
{

	if(t_receiver != NULL)
	{
		delete(t_receiver);	
		t_receiver=NULL;
	}
}

void 
ReceiverThread::run_independent_receiver()
{
	t_receiver = new thread(&Receiver::run_receiver, &udpCs);
}
void 
ReceiverThread::wait_for_receiver()
{
	t_receiver->join();
}

